<?php
/**
 * Created by PhpStorm.
 * User: mi
 * Date: 2018/8/12
 * Time: 11:16
 */

namespace Author;

class Author
{
    private $appId;
    private $appSecret;
    private $code;

    public function __construct($appId, $appSecret, $code)
    {
        $this->appId = $appId;
        $this->appSecret = $appSecret;
        $this->code = $code;
    }

    private function httpsGet($url)
    {
        $ch = curl_init($url);
        //3.设置参数
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
//        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);//跳过证书验证
//        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);  // 从证书中检查SSL加密算法是否存在
        //4.调用接口
        $res = curl_exec($ch);
        if (curl_errno($ch)) {
            var_dump(curl_error($ch));
        }
        $res = json_decode($res, 1);
        return $res;
    }

    private function getAccessToken()
    {
        $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=$this->appId&secret=$this->appSecret&code=$this->code&grant_type=authorization_code";
        $res = $this->httpsGet($url);
        var_dump($res);
        $assess_token = $res["access_token"];
        $openId = $res["openid"];
        var_dump($assess_token);
        return ["access_token" => $assess_token, "openId" => $openId];
    }

    public function getUserInfo()
    {
        $res = $this->getAccessToken();
        $assess_token = $res["access_token"];
        $openId = $res["openid"];
        $url = "https://api.weixin.qq.com/sns/userinfo?access_token=$assess_token&openid=$openId&lang=zh_CN";
        $userInfo = $this->httpsGet($url);
        $nickname = $userInfo["nickname"];
        $sex = $userInfo["sex"];
        $province = $userInfo["province"];
        $city = $userInfo["city"];
        $openid = $userInfo["openid"];
        $headimgurl = $userInfo["headimgurl"];

        $info = array(
            "nickname" => $nickname,
            "sex" => $sex,
            "province" => $province,
            "city" => $city,
            "openid" => $openId,
            "headimgurl" => $headimgurl,
        );
        return $info;
    }

}